<template>
  <div class="containers">
    <el-form label-width="100px">
      <el-form-item required label="报告通知人">
        <StaffTemplate :value="reportFormData.reportNotifierList" @change="(e) => handleNotifierChange(e)" />
      </el-form-item>
      <template v-for="(tabItem, tabIndex) in reportTypeList">
        <el-form-item :key="tabIndex" :label="tabItem.reportName + '配置'">
          <ReportTemplate :value="tabItem" @change="(e) => {handleInput(e, tabItem.reportType)}" />
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { reportTypeMap } from '@/config/dict'
import StaffTemplate from '@/containers/StaffTemplate'
import ReportTemplate from '../../ReportTemplate/index'
import { isValidArray } from '../../../../../../utils'
export default {
  name: 'ReportForm',
  components: { StaffTemplate, ReportTemplate },
  data() {
    return {
      reportTypeMap,
      reportTypeSelect: ''
    }
  },
  computed: {
    reportFormData: function() {
      return this.$store.state.businessFormData.reportForm.data || {}
    },
    reportTypeList: function() {
      const reportFormData = this.$store.state.businessFormData.reportForm.data || {}
      return reportTypeMap.map(e => {
        const current = (reportFormData.dataReportConfigParams || []).find(ee => ee.reportType === e.key)
        return { reportType: e.key, reportName: e.value, ...current }
      })
    }

  },
  watch: {
    reportFormData: {
      handler: function(val) {
        this.checkStatus(val)
      },
      immediate: true
    }
  },
  methods: {
    checkStatus(data) {
      let status = true
      const errMsg = []

      if (!isValidArray(data.reportNotifierList)) {
        status = false
        errMsg.push('请配置报告通知人')
      }

      if (!isValidArray(data.dataReportConfigParams)) {
        status = false
        errMsg.push('请至少配置一项报告配置')
      }

      const oldErrMsg = this.$store.state.businessFormData.reportForm.errMsg
      if (JSON.stringify(oldErrMsg) !== JSON.stringify(errMsg)) {
        this.$store.dispatch('businessFormData/setReportFormData', { status, errMsg })
      }
    },
    handleInput(e, reportType) {
      let dataReportConfigParams = this.reportFormData.dataReportConfigParams
      if (!dataReportConfigParams) {
        dataReportConfigParams = []
      }
      const index = dataReportConfigParams.findIndex(e => e.reportType === reportType)
      if (index === -1) {
        dataReportConfigParams.push(e)
      } else {
        dataReportConfigParams[index] = e
      }

      const result = { ...this.reportFormData, dataReportConfigParams }
      this.$store.dispatch('businessFormData/setReportFormData', { data: result })
    },
    handleNotifierChange(res) {
      const reportNotifierList = res
      const result = { ...this.reportFormData, reportNotifierList }
      this.$store.dispatch('businessFormData/setReportFormData', { data: result })
    }
  }
}
</script>

<style>

</style>
